package com.mayikt.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.elk.kafka.KafkaSender;
import com.mayikt.goods.output.dto.ProductDTO;
import com.mayikt.product.api.service.ProductSearchService;
import com.mayikt.product.es.entity.EsProduct;
import com.mayikt.product.es.repository.ProductRepository;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@Service
public class ProductSearchServiceImpl extends BaseApiService<List<ProductDTO>> implements ProductSearchService {
    @Autowired
    private ProductRepository productRepository;
    @Override
    public BaseResponse<List<ProductDTO>> search(String name) {
//        1.拼接查询条件
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
//        2.模糊查询name字段
        builder.must(QueryBuilders.fuzzyQuery("name",name));
        Pageable pageable = new QPageRequest(0, 5);
//        3.调用es接口查询
        Page<EsProduct> page = productRepository.search(builder,pageable);
//        4.获取集合数据
        List<EsProduct> esProductList = page.getContent();
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<ProductDTO> productDTOList = new ArrayList<>();
//        List<ProductDTO> productDTOList = mapperFactory.getMapperFacade().mapAsList(esProductList, ProductDTO.class);
        ProductDTO productDTO = new ProductDTO();
        for (EsProduct esProduct : esProductList) {
            BeanUtils.copyProperties(esProduct,productDTO);
            productDTOList.add(productDTO);
        }
        return setResultSuccess(productDTOList);
    }
}
